/**
 * Created by victor on 16/9/14.
 */
var mysql =  require('mysql');
var conf = require('../conf/db');
var util = require('../util/util');
var sql = require('../dao/marketSqlMapping');

//使用连接池
// var pool = mysql.createPool(util.extend({},conf.mysql));
var pool = mysql.createPool(conf.mysql);

//json简单封装
var jsonWrite = function (res,ret) {
    if (typeof res === 'undefined'){
        res.json({
            code:'1',
            msg:'操作失败'
        });
    } else {
        res.json(ret);
    }
};

module.exports = {
    queryByKeyWord:function (req,res,next) {
        //获取参数
        var param = req.query || req.param;
        var ret;
        pool.getConnection(function (err,connection) {
            connection.query(sql.queryByKeyWord,param.keyword,function (err,result) {
                //使用页面进行跳转提示
                if (result.length > 0 ){
                    var findReuslt = result[0];
                    var m_Id = findReuslt["market_id"];
                    var market_count = findReuslt["keyword_count"];
                    market_count = market_count + 1;
                    connection.query(sql.addRecords,[market_count,m_Id],function (err,result) {
                        if (result){
                            result = {
                                code:200,
                                msg:'增加成功'
                            };
                        }

                        jsonWrite(res,result);
                        //释放连接
                    });

                }else {
                    // res.render('fail',{
                    //     result:result
                    // });
                }
                console.log(result);
                connection.release();
                ret = result;
            });
        });
            return ret;
    },
    addRecords:function (req,res,next) {
        pool.getConnection(function (err,connection) {
            //获取参数
            var param = req.query || req.param;

            connection.query(sql.addRecords,param.keyword,function (err,result) {
                if (result){
                    result = {
                        code:200,
                        msg:'增加成功'
                    };
                }

                jsonWrite(res,result);
                //释放连接
                connection.release();

            });
        });
    },
    queryAll:function (req,res,next) {
        pool.getConnection(function (err,connection) {
            connection.query(sql.queryAll,function (err,result) {
                console.log(result);

                jsonWrite(res,result);
                connection.release();
            });
        });
    }
};


